import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { toast } from '@/lib/toast-with-audio';
import { useTheme } from '@/hooks/useTheme';
import { useSystem } from '@/contexts/SystemContext';
import { menuApi } from '@/store/menu';
import { Menu } from '@/types/menu';

// 状态徽章组件
const StatusBadge: React.FC<{ status: number }> = ({ status }) => {
  const statusText = status === 1 ? '启用' : '停用';
  const className = status === 1 
    ? 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300'
    : 'bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300';
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${className}`}>
      {statusText}
    </span>
  );
};

// 类型徽章组件
const TypeBadge: React.FC<{ type: number }> = ({ type }) => {
  let className = '';
  let typeText = '';
  
  switch (type) {
    case 0: // 系统
      className = 'bg-orange-100 dark:bg-orange-900 text-orange-700 dark:text-orange-300';
      typeText = '系统';
      break;
    case 1: // 菜单
      className = 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300';
      typeText = '菜单';
      break;
    case 2: // 目录
      className = 'bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300';
      typeText = '目录';
      break;
    default:
      className = 'bg-gray-100 dark:bg-gray-900 text-gray-700 dark:text-gray-300';
      typeText = '未知';
  }
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${className}`}>
      {typeText}
    </span>
  );
};

// 菜单项组件
interface MenuItemProps {
  menu: Menu;
  level?: number;
  onEdit: (menuId: string | number) => void;
  onToggleStatus: (menuId: string | number, currentStatus: number) => void;
}

const MenuItem: React.FC<MenuItemProps> = ({ menu, level = 0, onEdit, onToggleStatus }) => {
  const { isDark } = useTheme();
  const [isExpanded, setIsExpanded] = useState(true);
  
  const hasChildren = menu.children && menu.children.length > 0;
  const isSystem = menu.type === 0; // 0-系统
  
  const handleEdit = (menuId: string | number) => {
    onEdit(menuId);
  };
  
  const handleToggleStatus = (menuId: string | number, currentStatus: number) => {
    onToggleStatus(menuId, currentStatus);
  };
  
  return (
    <div>
      <div 
        className={`grid grid-cols-12 items-center p-4 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors ${
          level > 0 ? 'border-l-2 border-gray-200 dark:border-gray-600 ml-4' : ''
        } ${isSystem ? 'bg-gray-50 dark:bg-gray-800' : ''}`}
        style={{ paddingLeft: `${level * 20 + 16}px` }}
      >
        {/* 菜单名称列 */}
        <div className="col-span-4 flex items-center space-x-3">
          {hasChildren && (
            <button 
              onClick={() => setIsExpanded(!isExpanded)}
              className={`text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 ${isSystem ? 'text-lg' : 'text-sm'}`}
            >
              <i className={`fa-solid fa-chevron-${isExpanded ? 'down' : 'right'}`}></i>
            </button>
          )}
          {!hasChildren && <div className="w-4"></div>}
          
          <i className={`fa-solid ${menu.icon} ${isSystem ? 'text-xl' : 'text-base'} text-gray-500 dark:text-gray-400 w-5 text-center`}></i>
          
          <div>
            <div className={`font-medium ${isSystem ? 'text-lg' : 'text-base'} text-gray-800 dark:text-gray-100`}>{menu.name}</div>
            {menu.path && (
              <div className="text-xs text-gray-500 dark:text-gray-400">{menu.path}</div>
            )}
          </div>
        </div>
        
        {/* 排序列 */}
        <div className="col-span-2 text-center">
          <span className="text-sm text-gray-500 dark:text-gray-400">{menu.sort}</span>
        </div>
        
        {/* 类型列 */}
        <div className="col-span-2 text-center">
          <TypeBadge type={menu.type} />
        </div>
        
        {/* 状态列 */}
        <div className="col-span-2 text-center">
          <StatusBadge status={menu.status} />
        </div>
        
        {/* 操作列 */}
        <div className="col-span-2 text-right">
          <div className="flex space-x-2 justify-end">
            <button 
              className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 text-sm"
              onClick={() => handleEdit(menu.id)}
            >
              编辑
            </button>
            <button 
              className={menu.status === 1 ? 'text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 text-sm' : 'text-green-600 dark:text-green-400 hover:text-green-900 dark:hover:text-green-300 text-sm'}
              onClick={() => handleToggleStatus(menu.id, menu.status)}
            >
              {menu.status === 1 ? '禁用' : '启用'}
            </button>
          </div>
        </div>
      </div>
      
      {hasChildren && isExpanded && (
        <div>
          {menu.children.map((child: Menu) => (
            <MenuItem 
              key={child.id} 
              menu={child} 
              level={level + 1}
              onEdit={onEdit}
              onToggleStatus={onToggleStatus}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default function Menus() {
  const { isDark } = useTheme();
  const { systems } = useSystem();
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [systemFilter, setSystemFilter] = useState('all');
  const [menus, setMenus] = useState<Menu[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // 加载菜单数据
  useEffect(() => {
    loadMenus();
  }, []);
  
  const loadMenus = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await menuApi.getMenus({
        search: searchTerm || undefined,
        type: typeFilter !== 'all' ? (typeFilter === '系统' ? 0 : typeFilter === '菜单' ? 1 : 2) : undefined,
        status: statusFilter !== 'all' ? (statusFilter === '启用' ? 1 : 0) : undefined,
        parentId: systemFilter !== 'all' ? systemFilter : undefined
      });
      
      if (response.success) {
        setMenus(response.data);
      } else {
        setError(response.message || '获取菜单列表失败');
        toast.error(response.message || '获取菜单列表失败');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '网络请求失败';
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };
  
  // 处理搜索
  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      loadMenus();
    }
  };
  
  // 处理筛选条件变化
  useEffect(() => {
    loadMenus();
  }, [searchTerm, typeFilter, statusFilter, systemFilter]);
  
  // 创建菜单
  const handleCreateMenu = () => {
    toast('新建菜单功能开发中');
  };
  
  // 编辑菜单
  const handleEdit = async (menuId: string | number) => {
    try {
      const response = await menuApi.getMenu(menuId);
      if (response.success) {
        toast.info(`编辑菜单: ${response.data.name}`);
        // 这里可以打开编辑对话框
      } else {
        toast.error(response.message || '获取菜单详情失败');
      }
    } catch (err) {
      toast.error('获取菜单详情失败');
    }
  };
  
  // 切换菜单状态
  const handleToggleStatus = async (menuId: string | number, currentStatus: number) => {
    try {
      const newStatus = currentStatus === 1 ? 0 : 1;
      const response = await menuApi.toggleMenuStatus(menuId, newStatus);
      
      if (response.success) {
        toast.success(`菜单状态已${newStatus === 1 ? '启用' : '禁用'}`);
        loadMenus(); // 重新加载数据
      } else {
        toast.error(response.message || '切换菜单状态失败');
      }
    } catch (err) {
      toast.error('切换菜单状态失败');
    }
  };
  
  return (
    <div>
      <div className="mb-6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
        <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">菜单管理</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">管理系统菜单结构和权限</p>
        </motion.div>
      </div>
      
      {/* 工具栏 */}
      <motion.div 
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.3, delay: 0.1 }}
        className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <input 
              type="text" 
              placeholder="搜索菜单..." 
              className="py-2 pl-10 pr-4 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={handleSearch}
            />
            <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-500"></i>
          </div>
          
          <select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={systemFilter}
            onChange={(e) => setSystemFilter(e.target.value)}
          >
            <option value="all">全部系统</option>
            <option value="devops">DevOps系统</option>
            <option value="system">系统管理</option>
            <option value="help">帮助中心</option>
          </select>
          
          <select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value)}
          >
            <option value="all">全部类型</option>
            <option value="系统">系统</option>
            <option value="菜单">菜单</option>
            <option value="目录">目录</option>
          </select>
          
          <select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
          >
            <option value="all">全部状态</option>
            <option value="启用">启用</option>
            <option value="禁用">禁用</option>
          </select>
        </div>
        
        <button 
          className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
          onClick={handleCreateMenu}
        >
          <i className="fa-solid fa-plus mr-2"></i>
          新建菜单
        </button>
      </motion.div>
      
      {/* 菜单列表 */}
      <motion.div 
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 0.3, delay: 0.2 }}
        className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
        <div className="p-4 border-b border-gray-200 dark:border-gray-700">
          <div className="grid grid-cols-12 text-sm font-medium text-gray-500 dark:text-gray-400">
            <div className="col-span-4">菜单名称</div>
            <div className="col-span-2 text-center">排序</div>
            <div className="col-span-2 text-center">类型</div>
            <div className="col-span-2 text-center">状态</div>
            <div className="col-span-2 text-right">操作</div>
          </div>
        </div>
        
        <div>
          {loading ? (
            <div className="p-8 text-center text-gray-500 dark:text-gray-400">
              <i className="fa-solid fa-spinner fa-spin text-2xl mb-2"></i>
              <p>加载中...</p>
            </div>
          ) : error ? (
            <div className="p-8 text-center text-red-500 dark:text-red-400">
              <i className="fa-solid fa-exclamation-triangle text-2xl mb-2"></i>
              <p>{error}</p>
              <button 
                className="mt-2 bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
                onClick={loadMenus}
              >
                重新加载
              </button>
            </div>
          ) : menus.length === 0 ? (
            <div className="p-8 text-center text-gray-500 dark:text-gray-400">
              <i className="fa-solid fa-inbox text-2xl mb-2"></i>
              <p>暂无菜单数据</p>
            </div>
          ) : (
            menus.map((menu) => (
              <MenuItem 
                key={menu.id} 
                menu={menu} 
                onEdit={handleEdit}
                onToggleStatus={handleToggleStatus}
              />
            ))
          )}
        </div>
      </motion.div>
    </div>
  );
}